<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>game_room</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
</head>

<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px"></canvas>
            <!-- 显示区域 -->
            <div id="screen"> 准备开始... </div>
            <button class="return-btn" onclick="return_hall();">返回大厅</button>
        </div>
    </div>
    <script>
        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        let context = chess.getContext('2d');//获取chess控件的2d画布

        function initGame() {
            initBoard();
            context.strokeStyle = "#BFBFBF";
            // 背景图片
            let logo = new Image();
            logo.src = "https://millkbubble-blog-pic.oss-cn-guangzhou.aliyuncs.com/blogpic/202308150322847.png";
            logo.onload = function () {
                // 绘制图片
                context.drawImage(logo, 0, 0, 450, 450);
                // 绘制棋盘
                drawChessBoard();
            }
        }
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); //横向的线条
                context.stroke();
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); //纵向的线条
                context.stroke();
            }
        }
        //绘制棋子
        function oneStep(i, j, isWhite) {
            if (i==null || j==null) return;
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
        }
        //棋盘区域的点击事件
        chess.onclick = function (e) {
            if (is_over) {
                alert("游戏已结束，请返回大厅");
                return ;
            }

            //  1. 获取下棋位置，判断当前下棋操作是否正常
            //      1. 当前是否轮到自己走棋了
            //      2. 当前位置是否已经被占用
            //  2. 向服务器发送走棋请求
            if (!is_me) {
                alert("等待对方走棋....");
                return;
            }
            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            if (chessBoard[row][col] != 0) {
                alert("当前位置已有棋子！");
                return;
            }

            if (is_me)
            {
                is_me = false;
                oneStep(col, row, false);
                set_screen(false);
                //向服务器发送走棋请求
                send_chess(row, col);
            }
            
        }

        var ws_url = "ws://" + location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);
        var room_info = null;
        var is_me = true;
        var is_over = false;
        

        ws_hdl.onopen = function() {
            
            console.log("房间websocket建立成功");
        }

        ws_hdl.onclose = function() {
            console.log("房间websocket断开");
        }

        ws_hdl.onerror = function() {
            console.log("房间websocket连接错误");
        }

        ws_hdl.onmessage = function(evt) {
            if (is_over) {
                alert("游戏已结束，请返回大厅");
                return ;
            }

            var info = JSON.parse(evt.data);
            console.log(JSON.stringify(info));
            
            if (!info.result) {
                alert(info.reason);
                return;
            }
            if (info.optype == "unknow") {
                alert(info.reason);
                return;
            }

            if (info.optype == "room_ready") {
                room_info = info;
                is_me = !(room_info.self_id == room_info.white_id);
                set_screen(is_me);
                initGame();
            }
            else if (info.optype == "put_chess") {
                if (!info.result) {
                    alert(info.reason);
                    return;
                }
                // 绘制棋子
                is_me = info.uid == room_info.self_id ? false : true;
                var isWhite = info.uid == room_info.white_id ? true : false;
                oneStep(info.col, info.row, isWhite);
                set_screen(is_me);

                // 设置棋盘信息
                if (info.row != null && info.col != null) {
                    chessBoard[info.row][info.col] = 1;
                }
                
                // 判断是否胜利
                if (info.winner == 0) // 没有胜利者，游戏继续
                {
                    console.log("没有胜利，游戏继续");
                    return;
                }
                var screen_div = document.getElementById("screen");
                if (info.winner == room_info.self_id) {
                    screen_div.innerHTML = "您已获胜";
                }
                else {
                    screen_div.innerHTML = "对方获胜";
                }
                is_over = true;

                var chess_area_div = document.getElementById("chess_area");
                // var button_div = document.createElement("div");
                // button_div.innerHTML = "返回大厅";
                // button_div.onclick = function() {
                //     ws_hdl.close();
                //     location.replace("/game_hall.html");
                // }
                // var button_div = document.createElement("button"); // 改为使用 button 元素
                // button_div.className = "return-btn"; // 应用样式类
                // button_div.innerHTML = "返回大厅"; // 添加图标
                // button_div.onclick = function() {
                //     ws_hdl.close();
                //     location.replace("/game_hall.html");
                // }
                // chess_area_div.appendChild(button_div);
            }
            else if (info.optype == "chat") {
                var p_elem = document.createElement("p");
                p_elem.innerHTML = info.message;

                if (info.uid == room_info.self_id) {
                    p_elem.setAttribute("id", "self_msg");
                }
                else {
                    p_elem.setAttribute("id", "peer_msg");
                }

                var br_elem = document.createElement("br");

                var show_msg = document.getElementById("chat_show");
                show_msg.appendChild(p_elem);
                show_msg.appendChild(br_elem);
            }
        }

    </script>
</body>

<script>
    function set_screen(me) {
        var screen_div = document.getElementById("screen");
        if (me) {
            screen_div.innerHTML = "轮到己方走棋";
        } 
        else {
            screen_div.innerHTML = "轮到对方走棋";
        }
    }

    function send_chess(chess_row, chess_col) {
        var chess_info = {
            optype: "put_chess",
            room_id: room_info.room_id,
            uid: room_info.self_id,
            row: chess_row,
            col: chess_col
        };
        ws_hdl.send(JSON.stringify(chess_info));
        console.log(JSON.stringify(chess_info));
    }

    function return_hall() {
        ws_hdl.close();
        location.replace("/game_hall.html");
    }

</script>

</html>